// pages/shop/shop.js
const app = getApp()
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    brand:'请选择',
    norm:'请选择',
    caizi:'请选择',
    weight:'',
    SubmitbtnStatus:true, //true 提交,false 返回
    emitlist:[],
    remark:'',
    height:800,
    areaName:'',
    areaId:'',
    brandList: [],
    caiziList: [],
    normList: [],
    xuqiuList:[], //材质,型号吨位需求列表,存放材质,型号吨位的数组
    xuqiuAddForm:{},// 需求列表新添的 需要回显 材质,型号,吨位
    weightList: [],
    banner: [], //post图片
    chooseViewShowBanner:true,
    loadding:false,
    cityAreaArray: [],
    citysIndex: [0, 0],
    areaList: [],
    totalYunFeeList:[],//总共的运费列表
    //在选择材质的时候回显出型号和吨位，
    //多选的最后一个就是最新的把。
    postDataList: []//需要上传多个材质，就调用多次上传接口，

  },
  lifetimes: {
    attached: function () {
      //获得multiple组件  多选
      var tabHeight = ((44 + app.globalData.systemInfo.statusBarHeight) * (750 / app.globalData.systemInfo.windowWidth)); //将高度乘以换算后的该设备的rpx与px的比例
      this.setData({
        height: app.globalData.windowHeight - 120 - tabHeight
      })
      this.multiplebrand = this.selectComponent("#multiplebrand");
      this.multiplenorm = this.selectComponent("#multiplenorm");
      this.multipleweight = this.selectComponent("#multipleweight");
      this.multiplecaizi = this.selectComponent("#multiplecaizi");
      this.getDictTree();
      var that = this;
      app.request.postHeadForm('hgz/address/queryCityAndAreaList')
        .then(res => {
          that.setData({
            areaList: res.data
          })
          that.showAreaData2();
        })
      app.request.postHeadForm('hgz/dict/queryDictAndSubById/4').then(res =>{
        this.setData({
            totalYunFeeList:res.data.children
        })
      })

    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onShow: function () {

    },
    setLoc(area){
      this.setData({
        district: area
      }) 
    },
    showPicker(id,name){
      this.setData({
        areaName: name,
        areaId: id
      })
    },
    remarkput(e){
      this.setData({
        remark:e.detail.value
      })
    },
    getDictTree(){
      var that = this;
      app.request.postHeadForm('hgz/dict/getTree').then(res =>{
        var brandList = [];
        var normList = [];
        var caiziList = [];
        var weightList = [];
        for(var i=0;i<res.data.length;i++){
          if (res.data[i].dictName == '品牌'){
            brandList = res.data[i].children;
          } else if (res.data[i].dictName == '材质') {
            caiziList = res.data[i].children;
          } 
          
          // else if (res.data[i].dictName == '型号') {
          //   normList = res.data[i].children;
          // } else if (res.data[i].dictName == '吨位') {
          //   weightList = res.data[i].children;
          // }
        }
        that.setData({
          brandList: brandList,
          caiziList: caiziList,
          normList: [],
          weightList: []
        })
      });
    },
    _multiplecaiziConfirm(e) {
      console.log(e.detail);
      var mulitList = e.detail;
      var string = mulitList.dictName;
      var modelList = mulitList.children[0].children;
      // var weightList = mulitList.children[1].children;
      this.setData({
        normList: modelList,
        // weightList: weightList,
        norm: "请选择",
        weight: ""
      })

      this.setData({
        caizi: string,
      })
      this.multiplecaizi.hideMultiple();
    },
    _multipleweightConfirm(e) {
      var mulitList = e.detail;
      var string = "";
      for (var i = 0; i < mulitList.length; i++) {
        if (i == 0) {
          string = "" + mulitList[i].dictName;
        } else {
          string = string + "," + mulitList[i].dictName;
        }
      }
      this.setData({
        weight: string
      })
      this.multipleweight.hideMultiple();
    },
    _multiplenormConfirm(e) {
      var mulitList = e.detail;
      var string = mulitList.dictName;
      this.setData({
        norm: string
      })
      this.multiplenorm.hideMultiple();
    },
    //提交方案后查询
    queryLastEmit(){
      var params = {
        pageNum:1,
        pageSize:1000
      }
      app.request.postHeadForm('hgz/demand/querySelfListWithPage', params).then(res =>{
          if(res.data.list.length>0){
            this.queryEmitDetail(res.data.list[0].id);
          }
      })
    },
    //查询结果
    queryEmitDetail(id){
      app.request.postHeadForm('hgz/demand/queryPriceById/' + id)
      .then(res => {
        wx.hideLoading();
        var tabList = res.data;
        var totalYunFeeList = this.data.totalYunFeeList;
        if(tabList.length!=0){
          for(var i=0;i<totalYunFeeList.length;i++){
            if(tabList[0].brand == totalYunFeeList[i].dictValue){
                for(var j=0;j<tabList.length;j++){
                    // tabList[j].areaName;
                    var yunFee = 0;
                    if(totalYunFeeList[i].children!=null){
                        for(var k=0;k<totalYunFeeList[i].children.length;k++){
                            if(tabList[j].areaName == totalYunFeeList[i].children[k].dictName){
                              yunFee = totalYunFeeList[i].children[k].dictValue;
                              break;
                            }
                        }
                    }
                    console.log(yunFee);
                    tabList[j].price = tabList[j].price+Number(yunFee);
                    tabList[j].updateTm = tabList[j].updateTime.substring(5,16);
                }
                break;
            }
          }
        }
        this.setData({
          emitlist: tabList,
          SubmitbtnStatus:false
        })
      })
    },
    deletexuqiu(e){
      //删除某一个
      var index = e.currentTarget.dataset.index;
      console.log(e);
      var xuqiuList = this.data.xuqiuList;
      xuqiuList.splice(index,1);
      this.setData({
        xuqiuList:xuqiuList
      })
    },
    xuqiuwei(e){
      console.log(e);
      this.setData({
        weight:e.detail.value
      })
    },
    addxuqiu(){
      if (this.data.norm == '请选择' || this.data.norm == '') {
        wx.showToast({
          title: '请选择型号',
          icon: 'none',
          duration: 1000
        });
        return;
      }
      if (this.data.caizi == '请选择' || this.data.caizi == '') {
        wx.showToast({
          title: '请选择材质',
          icon: 'none',
          duration: 1000
        });
        return;
      }
      if (this.data.weight == '请输入' || this.data.weight == '') {
        wx.showToast({
          title: '请输入重量',
          icon: 'none',
          duration: 1000
        });
        return;
      }
      var xuqiuList = this.data.xuqiuList;
      xuqiuList.push({
        material:this.data.caizi,
        norm:this.data.norm,
        weight:this.data.weight
      })
      this.setData({
        xuqiuList:xuqiuList,
        norm:"",
        weight:""
      })

    },
    submit() {
      //点击返回
      if(!this.data.SubmitbtnStatus){
        this.setData({
          emitlist:[],
          SubmitbtnStatus:true
        })
        return;
      }
      if (this.data.areaId == '') {
        wx.showToast({
          title: '请选择地区',
          icon: 'none',
          duration: 1000
        });
        return;
      }
      if (this.data.brand == '请选择') {
        wx.showToast({
          title: '请选择品牌',
          icon: 'none',
          duration: 1000
        });
        return;
      }
      var imgPath = '';
      for (var i = 0; i < this.data.banner.length; i++) {
        if (imgPath == '') {
          imgPath = this.data.banner[0];
        } else {
          imgPath = imgPath + ";" + this.data.banner[i];
        }
      }
      var xuqiuList = this.data.xuqiuList;
      var materialStr = "";
      var normStr = "";
      var weightStr = "";
      if(xuqiuList.length == 0){
        if(this.data.caizi == "" ||  this.data.caizi == "请选择"){
          wx.showToast({
            title: '请添加材质',
            icon: 'none',
            duration: 1000
          });
          return;
        }
        if(this.data.norm == "" ||  this.data.norm == "请选择"){
          wx.showToast({
            title: '请添加型号',
            icon: 'none',
            duration: 1000
          });
          return;
        }
        if(this.data.weight == "" ||  this.data.weight == "请选择"){
          wx.showToast({
            title: '请输入吨位',
            icon: 'none',
            duration: 1000
          });
          return;
        }
        materialStr = this.data.caizi;
        normStr = this.data.norm;
        weightStr = this.data.weight;
      }else{
        for(var i=0;i<xuqiuList.length;i++){
          // if(materialStr.indexOf(xuqiuList[i].material) == -1){
            if(materialStr == ""){
              materialStr = xuqiuList[i].material;
            }else{
              materialStr = materialStr+","+xuqiuList[i].material;
            }
          // }
          // if(normStr.indexOf(xuqiuList[i].norm) == -1){
            if(normStr == ""){
              normStr = xuqiuList[i].norm;
            }else{
              normStr = normStr+","+xuqiuList[i].norm;
            }
          // }
          // if(weightStr.indexOf(xuqiuList[i].weight) == -1){
            if(weightStr == ""){
              weightStr = xuqiuList[i].weight;
            }else{
              weightStr = weightStr+","+xuqiuList[i].weight;
            }
          // }  
        }
      }
      var params = {
        areaId: this.data.areaId,
        brand: this.data.brand,
        material: materialStr,
        model: normStr,
        weight: weightStr,
        imgPath: imgPath,
        remark: this.data.remark,
      }
      var that = this;
      wx.showLoading({
        title: "上传中...",
        mask: true
      })
      app.request.postHeadForm('hgz/demand/save', params).then(res => {
        
        if (res.status) {
          wx.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 2000
          });
          that.queryLastEmit();
          that.setData({
            brand: '请选择',
            norm: '请选择',
            caizi: '请选择',
            weight: '',
            xuqiuList:[],
            banner: [],
            remark: ''
          })
        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.message,
            icon: 'error',
            duration: 2000
          });
        }
      })
    },
    _multiplebrandConfirm(e) {
      var mulitList = e.detail;
      var string = "";
      for(var i=0;i<mulitList.length;i++){
        if(i==0){
          string = "" + mulitList[i].dictName;
        }else{
          string = string+ "," + mulitList[i].dictName;
        }
      }
      this.setData({
        brand: string
      })
      this.multiplebrand.hideMultiple();
    },
    showAreaData2() {
      var that = this;
      var area = this.data.areaList;
      var district = wx.getStorageSync("area");
      var citysIndex = [0, 0];
      var areaName = '';
      var areaId = '';
      for (var i = 0; i < area.length; i++) {
        for (var j = 0; j < area[i].areaVoList.length; j++) {
          if (area[i].areaVoList[j].areaName == district) {
            citysIndex[0] = i;
            areaName = area[i].areaVoList[j].areaName;
            areaId = area[i].areaVoList[j].areaId;
            break;
          }
        }
      }
      var areaList = [
        [],
        []
      ];
      for (var i = 0; i < area.length; i++) {
        areaList[0].push(area[i].cityName);
        if (i == citysIndex[0]) {
          for (var j = 0; j < area[i].areaVoList.length; j++) {
            areaList[1].push(area[i].areaVoList[j].areaName);
          }
        }
      }
      that.setData({
        cityAreaArray: areaList,
        areaName: areaName,
        areaId: areaId
      })
    },
    showAreaData() {
      var that = this;
      var citysIndex = that.data.citysIndex;
      var area = this.data.areaList;
      var areaList = [
        [],
        []
      ];
      for (var i = 0; i < area.length; i++) {
        areaList[0].push(area[i].cityName);
        if (i == citysIndex[0]) {
          for (var j = 0; j < area[i].areaVoList.length; j++) {
            areaList[1].push(area[i].areaVoList[j].areaName);
          }
        }
      }

      that.setData({
        cityAreaArray: areaList
      })
    },
    bindRegionColumnChange(e) {
      //滑动事件触发
      var that = this;
      var citysIndex = this.data.citysIndex;
      citysIndex[e.detail.column] = e.detail.value;
      that.setData({
        citysIndex: citysIndex
      })
      if (e.detail.column == 0) {
        that.showAreaData();
      }
    },
    bindRegionChange(e) {
      //确认按钮触发
      console.log(e);
      var areabyte = e.detail.value;
      var areaList = this.data.cityAreaArray[1];
      var areaName = areaList[areabyte[1]];
      console.log(areaName);
      var area = this.data.areaList;
      var areaId = '';
      for (var i = 0; i < area.length; i++) {
        for (var j = 0; j < area[i].areaVoList.length; j++) {
          if (area[i].areaVoList[j].areaName == areaName) {
            areaId = area[i].areaVoList[j].areaId;
            break;
          }
        }
      }
      this.setData({
        areaName: areaName,
        areaId: areaId
      })
    },

    showCaizi: function () {
      this.multiplecaizi.showMultiple();
    },
    showBrand: function () {
      this.multiplebrand.showMultiple();
    },
    showNorm: function () {
      if(this.data.normList.length>1){
        this.multiplenorm.showMultiple();
      }else{
        wx.showToast({
          title: '请先选择材质',
          icon:'none'
        })
      }
    },
    showWeight: function () {
      this.multipleweight.showMultiple();
    },
    _multiplebrandCancel() {
      this.multiplebrand.hideMultiple();
    },
    _multiplecaiziCancel() {
      this.multiplecaizi.hideMultiple();
    },
    _multipleweightCancel() {
      this.multipleweight.hideMultiple();
    },
    _multiplenormCancel() {
      this.multiplenorm.hideMultiple();
    },
    /** 选择图片Banner */
    chooseBanner: function () {
      var that = this;
      if (this.data.banner.length < 3) {
        wx.chooseImage({
          count: 1, //最多选择3张图片- that.data.banner.length,
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: function (res) {
            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
            if (res.tempFilePaths.count == 0) {
              return;
            }
            wx.showLoading({
              title: "上传中...",
              mask: true
            })
            console.log(res)
              
            wx.uploadFile({
              filePath: res.tempFilePaths[0],
              name: 'file',
              url: 'https://www.hangangzao.com/lot/weixin/open/upload',
              header: {
                'content-type': 'multipart/form-data',
                'accept': 'application/json',
              },
              success(res) {
                wx.hideLoading();
                let data = JSON.parse(res.data); // 这个很关键
                var imgArrNow = that.data.banner;
                imgArrNow = imgArrNow.concat(data.data.url);
                that.setData({
                  banner: imgArrNow
                })
                that.chooseViewShowBanner();
              }
            })
          }
        })
      } else {
        wx.showToast({
          title: '限制选择3个文件',
          icon: 'loading',
          duration: 1000
        })
      }
    },
    /** 删除图片Banner */
    deleteImvBanner: function (e) {
      var banner = this.data.banner;
      var itemIndex = e.currentTarget.dataset.id;
      banner.splice(itemIndex, 1);
      this.setData({
        banner: banner
      })
      //判断是否隐藏选择图片
      this.chooseViewShowBanner();
    },
    /** 是否隐藏图片选择Banner*/
    chooseViewShowBanner: function () {
      if (this.data.banner.length >= 3) {
        this.setData({
          chooseViewShowBanner: false
        })
      } else {
        this.setData({
          chooseViewShowBanner: true
        })
      }
    },
    /** 查看大图Banner */
    showImageBanner: function (e) {
      var banner = this.data.banner;
      var itemIndex = e.currentTarget.dataset.id;
      wx.previewImage({
        current: banner[itemIndex], // 当前显示图片的http链接
        urls: banner // 需要预览的图片http链接列表
      })
    },
  }
})
